package com.newspublish.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newspublish.system.entity.system.Comment;
import com.newspublish.system.entity.system.SysUser;
import com.newspublish.system.mapper.CommentMapper;
import com.newspublish.system.mapper.SysUserMapper;
import com.newspublish.system.service.CommentService;
import com.newspublish.system.utils.result.Result;
import com.newspublish.system.utils.util.GetMassege;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    private GetMassege getMassege;

    //获取所有评论
    @Override
    public Result getALLComments(){
        List<Comment> comments=commentMapper.selectAllComments();
        return Result.ok(comments);
    }
    //添加一级评论
    @Override
    public Result addComment(Comment comment) {
        String user= getMassege.getUser();
        SysUser sysUser=sysUserMapper.selectByUsername(user);
        String avatarUrl=sysUser.getHeadUrl();
        String nickName=user;
        comment.setUsername(user);
        comment.setAvatarUrl(avatarUrl);
        comment.setNickName(nickName);
        comment.setAuditStatus("待审核");
        commentMapper.insert(comment);
        return Result.ok(comment).message("评论成功");
    }

    //在一级评论下添加二级评论
    @Override
    public Result addCommentLevel2(Comment comment) {
        //传进来的参数要有父亲的id，也就是parentId，
        //然后设置这条评论的父亲（在接收参数时已经自动封装）
        String user = getMassege.getUser();
        SysUser sysUser = sysUserMapper.selectByUsername(user);
        String avatarUrl = sysUser.getHeadUrl();
        String nickName = user;
        comment.setUsername(user);
        comment.setAvatarUrl(avatarUrl);
        comment.setNickName(nickName);
        comment.setAuditStatus("待审核");
        commentMapper.insert(comment);
        return Result.ok(comment).message("回复成功");
    }

    //管理员获取谋篇文章下的所有评论
    @Override
    public Result getAllCommentOne(Integer pageNum,Long newsId) {
        // 创建page对象
        Page<Comment> pageParam = new Page<>(pageNum, 5);
//        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("auditStatus", "审核通过");
//        Page<Comment> commentPage = commentMapper.selectPage(pageParam, null);
//        List<Comment> comments = commentPage.getRecords();
        List<Comment> comments=commentMapper.selectCOmmentsByOne(newsId,"审核通过");
        return Result.ok(comments);
    }

    //管理员删除评论
    @Override
    public Result deleteCommentByAdmin(Long id) {

        //递归删除
        Comment comment =new Comment();
        comment.setCommentId(id.intValue());
        int i=deepSearchDelete(comment);

        //然后删除父评论 使用mybatisplus  待补充
        commentMapper.deleteById(id);
        if(i<0){
            return Result.fail().message("删除失败");
        }else{
            return Result.ok().message("删除成功");
        }

    }

    //本人删除自己的评论
    @Override
    public Result deleteCommentByI(Long id, String username) {
        if(!commentMapper.selectByPrimaryKey(id).getUsername().equals(username)){
            return Result.fail().message("删除失败");
        }
        //先删除子儿子  也可以使用级联删除  这里先使用递归删除
        Comment comment =new Comment();
        comment.setCommentId(id.intValue());
        int i = deepSearchDelete(comment);
        //删除父评论
        commentMapper.deleteById(id);
        if (i<0) {
            return Result.fail().message("删除失败");
        }
         return Result.ok().message("删除成功");
    }

    //点赞评论
    @Override
    public Result likeComment(Long id) {
        commentMapper.like(id);
        return Result.ok().message("点赞+1");
    }

    //根据id获取评论详情  mybatisplus
    @Override
    public Result getDetailById(Long id) {
        Comment comment =new Comment();
        comment =commentMapper.selectByPrimaryKey(id);
        System.out.println("1111"+comment);
        return Result.ok(comment).message("获取成功");
    }

    /**
     * 管理员获取子评论
     * @param comment
     */
    public void deepSearchManager(Comment comment){
        System.out.println(comment);
        if (comment!=null) {
            List<Comment> commentList = commentMapper.selectByParentId(comment.getCommentId(),"审核通过");
            if (!CollectionUtils.isEmpty(commentList)) {
                for (Comment vo : commentList) {
                    comment.setCommentList(commentList);
                    deepSearchManager(vo);
                }
            }
        }
    }

    /**
     * 普通用户获取子评论
     */
    //    深度优先遍历子节点，获取子评论,按日期降序，点赞数降序排序
    public void deepSearch(Comment comment){
//        System.out.println(comment);
//        第一次调用此方法，传进来根节点的id（一级评论id）
//        往后递归调用，传进来的是上一节点的id
//        判断有没有内容
//        如果有，渲染
        if (comment !=null) {
//            找儿子
            List<Comment> commentList = commentMapper.selectByParentId(comment.getCommentId(),"待审核");
//            System.out.println(commentList);
//            判断有没有儿子
            if (!CollectionUtils.isEmpty(commentList)) {
//                可能有多个儿子，要循环遍历每个儿子
                for (Comment vo : commentList) {
                    comment.setCommentList(commentList);
//                    递归调用，通过儿子找孙子，往下无限延伸，直到最底层，然后返回上一层
                    deepSearch(vo);
                }
            }
        }
    }

    //递归删除
    public int deepSearchDelete(Comment comment){

        if (comment !=null) {
            //查询所有父评论ID为当前评论ID的评论列表
            List<Comment> commentList = commentMapper.selectByParentIdCuster(comment.getCommentId());
            if (!CollectionUtils.isEmpty(commentList)) {
                for (Comment vo : commentList) {
                    //将commentList设置为当前评论对象Comment的列表
                    comment.setCommentList(commentList);
                    //再次查找父评论下面的子评论
                    deepSearchDelete(vo);
                }
            }
            return commentMapper.deleteByParentId(Long.valueOf(comment.getCommentId()));
        }
        return 0;
    }
}
